package service.impl;

import mapper.SupplierMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import pojo.Page;
import pojo.Supplier;
import service.SupplierService;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Transactional(rollbackFor = {Exception.class})
@Service
public class SupplierServiceImpl implements SupplierService {
    @Resource
    private SupplierMapper supplierMapper;

    @Transactional(readOnly = true,propagation = Propagation.NOT_SUPPORTED)
    @Override
    public List<Supplier> select(String supCode, String supName, Page page) {
        int count=supplierMapper.count(supCode,supName);
        page.setTotalCount(count);
        if (page.getCurPage()>page.getTotalPage()){
            page.setCurPage(page.getTotalPage());
        }
        if (page.getCurPage()<=0){
            page.setCurPage(1);
        }
        int pageIndex=(page.getCurPage()-1)*page.getPageSize();
        page.setList(supplierMapper.select(supCode,supName,pageIndex,page.getPageSize()));
        return page.getList();
    }

    @Override
    public int add(Supplier sup) {
        int result=0;
        try {
            if (supplierMapper.add(sup)>0){
                result=1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public int updateSupplier(Supplier supplier) {
        int result=0;
        try {
            if (supplierMapper.updateSupplier(supplier)>0){
                result=1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public int del(String id) {
        int result=0;
        Supplier supplier=supplierMapper.getSupplierById(id);
        try {
            if (supplier.getCompanyLicPicPath()!=null){
                File file=new File("D:\\SSMProjects\\out\\artifacts\\Chapter10_war_exploded"+supplier.getCompanyLicPicPath());
                file.delete();
            }
            if (supplier.getOrgCodePicPath()!=null){
                File file=new File("D:\\SSMProjects\\out\\artifacts\\Chapter10_war_exploded"+supplier.getOrgCodePicPath());
                file.delete();
            }
            if (supplierMapper.del(id)>0){
                result=1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Transactional(readOnly = true,propagation = Propagation.NOT_SUPPORTED)
    @Override
    public Supplier getSupplierById(String id) {
        return supplierMapper.getSupplierById(id);
    }
}
